package com.magina.machine.config;

import com.magina.machine.config.persister.InMemoryStateMachinePersist;
import com.magina.machine.config.persister.OrderStateMachinePersist;
import com.magina.machine.model.DemoClass;
import com.magina.machine.model.OrderMachinaData.*;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.statemachine.StateMachinePersist;
import org.springframework.statemachine.persist.DefaultStateMachinePersister;
import org.springframework.statemachine.persist.RepositoryStateMachinePersist;
import org.springframework.statemachine.persist.StateMachinePersister;
import org.springframework.statemachine.redis.RedisStateMachineContextRepository;
import org.springframework.statemachine.redis.RedisStateMachinePersister;
import org.springframework.web.client.RestTemplate;

@Configuration
public class Config {

    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
        return builder.build();
    }

    @Autowired
    private InMemoryStateMachinePersist inMemoryStateMachinePersist;

    @Autowired
    private RedisConnectionFactory redisConnectionFactory;

    @Autowired
    private OrderStateMachinePersist orderStateMachinePersist;

    /**
     * 注入StateMachinePersister对象
     *
     * @return
     */
    @Bean(name="orderMemoryPersister")
    public StateMachinePersister<OrderStates, OrderEvents, String> getPersister() {
        return new DefaultStateMachinePersister<>(inMemoryStateMachinePersist);
    }

    /**
     * 注入RedisStateMachinePersister对象
     *
     * @return
     */
    @Bean(name = "orderRedisPersister")
    public RedisStateMachinePersister<OrderStates, OrderEvents> redisPersister() {
        return new RedisStateMachinePersister<>(redisPersist());
    }

    /**
     * 通过redisConnectionFactory创建StateMachinePersist
     * @return
     */
    public StateMachinePersist<OrderStates, OrderEvents,String> redisPersist() {
        RedisStateMachineContextRepository<OrderStates, OrderEvents> repository = new RedisStateMachineContextRepository<>(redisConnectionFactory);
        return new RepositoryStateMachinePersist<>(repository);
    }

    @Bean(name="beanPersister")
    public StateMachinePersister<OrderStates, OrderEvents, DemoClass> orderPersister() {
        return new DefaultStateMachinePersister<OrderStates, OrderEvents, DemoClass>(orderStateMachinePersist);
    }
}
